﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using ywxt.Common;

namespace ywxt.NewsPush.Controllers
{
    using DB_NH;
    using NHibernate;
    using NHibernate.Criterion;
    using NHibernate.Linq;


    public class AccountController : Controller
    {
        //
        // GET: /Account/

        [AllowAnonymous]
        public ActionResult Login(string ReturnUrl)
        {
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(string UserName, string Password, bool RememberMe, string ReturnUrl)
        {
            if (ModelState.IsValid)
            {
                #region 进行自定义验证。（取消进行域验证，域验证通过后，才能进行Form认证）
                var UserDomain = System.Configuration.ConfigurationManager.AppSettings["AppDomain"];

                var sessionFactory = SessionFactory.GetCurrentFactory();
                using (var session = sessionFactory.OpenSession())
                using (var transaction = session.BeginTransaction())
                {
                    try
                    {
                        /*
                        //数据库认证
                        AuthenticatedUser user = (from d in session.Query<DB_NH.DB_Model.ywxt.t_sys_user>()
                                where d.is_valid == 1
                                && d.user_loginname == UserName
                                && d.user_password == Password
                                orderby d.create_date descending
                                select new AuthenticatedUser()
                                {
                                    Company=d.department.dept_name,
                                    Department = d.department.dept_name,
                                    DisplayName=d.user_truename_cn,
                                    ID=d.user_id,
                                    Mail=d.sp_mail,
                                    Mobile=d.user_mobilephone,
                                    Name=d.user_truename_en,
                                    RoleGroups=d.user_roles.Split(new char[] { ',' },StringSplitOptions.RemoveEmptyEntries).ToList()
                                }).FirstOrDefault();
                        //*/

                        //*
                        //域认证
                        AuthenticatedUser user = ywxt.Common.Common.ADIdentify(UserDomain, UserName, Password);
                        //*/

                        if (user != null)
                        {
                            string uData = Newtonsoft.Json.JsonConvert.SerializeObject(user);

                            //* 普通cookie的用法
                            //登录域的用户，通过验证
                            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                    1,
                                    user.DisplayName,
                                    DateTime.Now,
                                    DateTime.Now.Add(FormsAuthentication.Timeout),
                                    RememberMe,
                                    uData
                                    );
                            HttpCookie cookie = new HttpCookie(
                                FormsAuthentication.FormsCookieName,
                                FormsAuthentication.Encrypt(ticket));
                            cookie.Expires = DateTime.Now.Add(FormsAuthentication.Timeout);
                            Response.Cookies.Add(cookie);

                            if (Url.IsLocalUrl(ReturnUrl))
                            {
                                return Redirect(ReturnUrl);
                            }
                            else
                            {
                                return RedirectToAction("Index", "Home");
                            }
                        }
                        else
                        {
                            transaction.Rollback();
                            return View();
                        }

                    }
                    catch (Exception ex)
                    {
                        ModelState.AddModelError("", ex.Message);
                    }

                }


                #endregion
            }

            // If we got this far, something failed, redisplay form
            return View();
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            HttpCookie cookie = Response.Cookies[FormsAuthentication.FormsCookieName];
            //cookie.Domain = cookieDomain;
            cookie.Value = null;
            cookie.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Add(cookie);

            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "Account");
        }

    }
}
